package com.s3u4.concurrence.cas;

import sun.misc.Unsafe;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * Created by Captain on 30/03/2018.
 */
public class MyAtomicInteger {

    private volatile int value;
    private static final Unsafe unsafe = Unsafe.getUnsafe();
    private static final long valueOffset;

    static {
        try {
            valueOffset = unsafe.objectFieldOffset
                    (AtomicInteger.class.getDeclaredField("value"));
        } catch (Exception ex) { throw new Error(ex); }
    }

    public MyAtomicInteger(int v){
        this.value = v;
    }

    public int get(){
        return value;
    }

    public void increment(){
        unsafe.getAndAddInt(this,valueOffset,1);
    }

    public static void main(String[] args) throws InterruptedException {
        MyAtomicInteger atomicInteger = new MyAtomicInteger(0);
        ExecutorService executorService = Executors.newFixedThreadPool(10);
        for ( int i = 0 ; i <= 100 ; i++ ){
            executorService.execute( () -> {
                atomicInteger.increment();
            });
        }

        Thread.sleep(2000);
        System.out.println(atomicInteger.get());

        executorService.shutdown();
    }

}
